import config from '@/config'
import {
	getToken,
	setToken
} from '@/utils/auth'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import Request from 'luch-request'

let timeout = 10000
const baseUrl = config.baseUrl

const http = new Request()

// 请求前拦截，添加header头
http.interceptors.request.use((conf) => {
	conf.baseURL = baseUrl
	if (getToken()) {
		conf.header.Authorization = 'Bearer ' + getToken()
	}
	uni.showLoading({
		title: '加载中'
	})
	return conf
}, conf => {
	return Promise.reject(conf)
})

// 请求后拦截
http.interceptors.response.use((rep) => {
	const code = rep.data.code || 200
	uni.hideLoading()
	if (rep.config.url === "/login") {
		if (code == 200) {
			setToken(rep.data.data.token)
			uni.setStorageSync("userinfo", rep.data.data)
		}
	}
	if (code === 401) {
		uni.clearStorageSync()
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				http.post('/login', {
					code: loginRes.code
				})
			}
		})
		return Promise.reject(rep)
	} else if (code === 500) {
		toast(rep.data.msg || '获取数据失败')
		return Promise.reject(rep)
	}else if(code !== 200) {
		return Promise.resolve(rep.data)
	} else {
		return Promise.resolve(rep.data.data)
	}
}, (rep) => {
	uni.hideLoading()
	toast('获取数据失败')
	return Promise.reject(rep)
})


export default http